/*
 * Copyright Dan A. "devastator" Haman <dan.haman at yahoo.co.uk>, 2010.
 *
 * This file is part of MassMurderer System.
 *
 * MassMurderer System is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MassMurderer System is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MassMurderer System.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * CustomNet.java
 * 17:30:33 04.04.2010
 */
package ua.edu.donnu.massmurderer.admin;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import ua.edu.donnu.massmurderer.admin.models.IpListModel;

/**
 *
 * 17:30:33 04.04.2010
 * @author Dan A. "devastator" Haman <dan.haman at yahoo.co.uk>
 * @version 1.0
 */
public class CustomNet extends JDialog {

    /**
     * list datamodel
     */
    private IpListModel lmModel = new IpListModel();
    /**
     * selected addresss list
     */
    private Inet4Address[] jnSendTo = null;

    /** Creates new form CustomNet */
    public CustomNet(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        try {
            initComponents();
            initListData();
        } catch (UnknownHostException ex) {
            MurderConsole.lgInst.severe(ex.getLocalizedMessage());
        }
    }

    /**
     * initializing list data with local adapters info
     * @since 1.0
     * @throws UnknownHostException
     */
    protected void initListData() throws UnknownHostException {
        InetAddress[] jnAdrs = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
        for (int i = 0; i < jnAdrs.length; i++) {
            lmModel.addElement((changeLast(jnAdrs[i], (byte) 0)).getHostAddress());
        }
        if (lmModel.getSize() == 1) {
            jList1.setSelectedIndex(0);
        }
    }

    /**
     * getting results (list of network addresses to turn off)
     * @since 1.0
     * @return list of addresses
     */
    public Inet4Address[] getResult() throws UnknownHostException {
        jnSendTo = new Inet4Address[lmModel.getSize()];
        for (int i = 0; i < jnSendTo.length; i++) {
            jnSendTo[i] = (Inet4Address) InetAddress.getByName(String.valueOf(lmModel.getElementAt(i)));
            jnSendTo[i] = (Inet4Address) changeLast(jnSendTo[i], (byte) 255);
        }
        return jnSendTo;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        pBts = new javax.swing.JPanel();
        bApply = new javax.swing.JButton();
        bCancel = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jPanel3 = new javax.swing.JPanel();
        txNew = new javax.swing.JTextField();
        bAdd = new javax.swing.JButton();
        bRemove = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(MurderConsole.joLocalization.getString("ttlNetwork"));

        pBts.setMinimumSize(new java.awt.Dimension(100, 40));
        pBts.setPreferredSize(new java.awt.Dimension(400, 40));

        bApply.setText(MurderConsole.joLocalization.getString("bApply"));
        bApply.setToolTipText(MurderConsole.joLocalization.getString("tpApply"));
        bApply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bApplyActionPerformed(evt);
            }
        });
        pBts.add(bApply);

        bCancel.setText(MurderConsole.joLocalization.getString("bCancel"));
        bCancel.setToolTipText(MurderConsole.joLocalization.getString("tpCancel"));
        bCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCancelActionPerformed(evt);
            }
        });
        pBts.add(bCancel);

        getContentPane().add(pBts, java.awt.BorderLayout.SOUTH);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jList1.setModel(lmModel);
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel3.setPreferredSize(new java.awt.Dimension(400, 40));
        jPanel3.setLayout(new java.awt.GridBagLayout());

        txNew.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txNewKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 0.4;
        jPanel3.add(txNew, gridBagConstraints);

        bAdd.setText(MurderConsole.joLocalization.getString("bAdd2"));
        bAdd.setToolTipText(MurderConsole.joLocalization.getString("tpAdd2"));
        bAdd.setEnabled(false);
        bAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAddActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        jPanel3.add(bAdd, gridBagConstraints);

        bRemove.setText(MurderConsole.joLocalization.getString("bRemove2"));
        bRemove.setToolTipText(MurderConsole.joLocalization.getString("tpRemove2"));
        bRemove.setEnabled(false);
        bRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bRemoveActionPerformed(evt);
            }
        });
        jPanel3.add(bRemove, new java.awt.GridBagConstraints());

        jPanel2.add(jPanel3, java.awt.BorderLayout.SOUTH);

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAddActionPerformed
        if (!txNew.getText().isEmpty()) {
            try {
                lmModel.addElement(changeLast(InetAddress.getByName(txNew.getText()), (byte) 0).getHostAddress());
                txNew.setText("");
            } catch (UnknownHostException ex) {
                MurderConsole.lgInst.severe(ex.getLocalizedMessage());
            }
        }
    }//GEN-LAST:event_bAddActionPerformed

    private void bRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRemoveActionPerformed
        lmModel.removeElement(String.valueOf(jList1.getSelectedValue()));
    }//GEN-LAST:event_bRemoveActionPerformed

    private void bCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelActionPerformed
        lmModel.clearModel();
        this.setVisible(false);
    }//GEN-LAST:event_bCancelActionPerformed

    private void bApplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bApplyActionPerformed
        try {
            jnSendTo = new Inet4Address[jList1.getSelectedValues().length];
            for (int i = 0; i < jnSendTo.length; i++) {
                jnSendTo[i] = (Inet4Address) InetAddress.getByName(String.valueOf(jList1.getSelectedValues()[i]));
            }
        } catch (UnknownHostException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), MurderConsole.joLocalization.getString("dlgError"), JOptionPane.ERROR_MESSAGE);
            MurderConsole.lgInst.severe(ex.getMessage());
        }
        this.setVisible(false);
    }//GEN-LAST:event_bApplyActionPerformed

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
        bRemove.setEnabled(!jList1.isSelectionEmpty());
    }//GEN-LAST:event_jList1ValueChanged

    /**
     * checking whether input string is of a valid IP address format
     * @param sAdr string ip to check
     * @return true if <i>sAdr</i> is valid, false otherwise
     */
    public static boolean isValidAdr(String sAdr) {
        try {
            InetAddress.getByName(sAdr);
            return true;
        } catch (UnknownHostException ex) {
        }
        return false;
    }

    /**
     * changing the last byte of IP address to specified value
     * @param jnAdr address to change
     * @param bValue new last byte value
     * @return modified IP address
     * @throws UnknownHostException
     */
    public static InetAddress changeLast(InetAddress jnAdr, byte bValue) throws UnknownHostException {
        byte[] bAdr = jnAdr.getAddress();
        bAdr[bAdr.length - 1] = bValue;
        return InetAddress.getByAddress(bAdr);
    }

    private void txNewKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txNewKeyReleased
        bAdd.setEnabled(isValidAdr(txNew.getText()));
    }//GEN-LAST:event_txNewKeyReleased
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bAdd;
    private javax.swing.JButton bApply;
    private javax.swing.JButton bCancel;
    private javax.swing.JButton bRemove;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel pBts;
    private javax.swing.JTextField txNew;
    // End of variables declaration//GEN-END:variables
}
